import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import storage from '@/utils/storage';
import { usePeimissionStore } from '@/store/permission';
import { userStore } from '@/store/user';
import { defineAsyncComponent } from 'vue';
// console.log(peimission);
const routes: Array<RouteRecordRaw> = [
    {
        path: '/redirect',
        component: () => import('@/pages/layout/index.vue'),
        children: [
            {
                path: '/redirect/:path*',
                component: () => import('@/pages/layout/index.vue'),
            },
        ],
    },
    {
        path: '/',
        name: 'layout',
        redirect: '/home',
        meta: {
            title: '系统',
        },
        component: () => import('@/pages/layout/index.vue'),
        children: [
            {
                path: '/home',
                name: '首页',
                meta: {
                    title: '首页',
                    icon: 'House',
                },
                component: () => import('@/pages/home/index.vue'),
            },
        ],
    },

    {
        path: '/login',
        name: 'login',
        meta: {
            title: '登陆',
        },
        component: () => import('@/pages/login/index.vue'),
    },
    // {
    //     path: '/404',
    //     name: '404',
    //     component: () => import('@/pages/error-page/404.vue'),
    // },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});
export function resetRouter() {
    routes.forEach((route: any) => {
        router.removeRoute(route.name);
    });
}
// 角色权限，动态路由
const whiteList: string[] = ['/login', '/404'];
let pageRefresh = true;

router.beforeEach(async (to, from) => {
    // 如果是login或者404页面直接跳转过去
    if (whiteList.indexOf(to.path) !== -1) {
        if (to.path == '/login') {
            pageRefresh = true;
        }
        return true;
    }
    // 获取token，如果用户没登录，则跳转登录页面
    if (!storage.get('token') && to.path !== '/login') {
        router.push({
            path: 'login',
            query: {
                redirect: to.path,
            },
        });
    } else {
        //如果为true说明已添加过直接跳过
        if (!pageRefresh) {
            return true;
        } else {
            //后端获取动态路由
            const user = userStore();
            user.getInfos();
            const peimission = usePeimissionStore();
            peimission.generateRoutes().then((res: any) => {
                // // 没有子路由时则回首页
                if (res && to.matched.length === 0) {
                    router.push(to.fullPath);
                }
            });
            pageRefresh = false;
        }
    }
});
export { router, routes };
